package com.qiantu.phone.ui.activity.map;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiSearch;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.base.BaseActivity;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.entity.LinkageBean;
import com.qiantu.phone.R;
import com.qiantu.phone.aop.Permissions;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.bean.LocationData;
import com.qiantu.phone.ui.activity.EditLinkageActivity;
import com.qiantu.phone.utils.LinkageDataHolder;
import com.qiantu.phone.utils.LocationUtil;
import com.qiantu.phone.widget.MySeekBar;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.ACCESS_BACKGROUND_LOCATION;

public class LocationActivity extends AppActivity implements GeocodeSearch.OnGeocodeSearchListener, Inputtips.InputtipsListener, AMapLocationListener {

    public static final int LOCATION_REQUEST_CODE = 1000;

    MapView map;
    private int range = 0;
    MapOverlyView mapOver;
    private String inputStr = "";
    RecyclerView locList;
    TextView tvSearchNoData;
    private LocationData mLocationData;
    private RegeocodeResult regeocodeResult;
    private Boolean isSearching = false;
    EditText etAddr;
    private View searchLine;
    private View space;
    private TextView tvRangeLabel;
//    private RadioGroup rangeRadioGroup;
    private MySeekBar mSeekBar;
    XXPermissions xxPermissions;
    private boolean isMoveToLocation = false;
    //0具体位置 1室外环境位置 2设置联动定位条件
    private int type;
    /**
     * 需要进行检测的权限数组
     */
    protected String[] needPermissions = {
            ACCESS_COARSE_LOCATION,
            ACCESS_FINE_LOCATION,
            ACCESS_BACKGROUND_LOCATION
    };
    //如果设置了target > 28，需要增加这个权限，否则不会弹出"始终允许"这个选择框
    private static String BACKGROUND_LOCATION_PERMISSION = "android.permission.ACCESS_BACKGROUND_LOCATION";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        map = findViewById(R.id.map);
        map.onCreate(savedInstanceState);
        mapOver = findViewById(R.id.map_over);
        etAddr = findViewById(R.id.et_addr);
        searchLine = findViewById(R.id.search_line);
        space = findViewById(R.id.space);
        locList = findViewById(R.id.loc_list);
        tvSearchNoData = findViewById(R.id.tv_search_no_data);
        tvRangeLabel = findViewById(R.id.tv_range_label);
//        rangeRadioGroup = findViewById(R.id.range_radio_group);
        mSeekBar = findViewById(R.id.my_seek_bar);
        mLocationData = (LocationData) getIntent().getSerializableExtra("DATA");
        type = getIntent().getIntExtra("type", 0);
        aMap = map.getMap();
        switch (type){
            case 0:
                range = 0;
                etAddr.setHint(R.string.specific_location_hint);
                setTitle(R.string.specific_location);
                tvRangeLabel.setVisibility(View.GONE);
//                rangeRadioGroup.setVisibility(View.GONE);
                mSeekBar.setVisibility(View.GONE);
                break;
            case 1:
//                if(mLocationData != null && mLocationData.scopeLong > 0){
//                    range = mLocationData.scopeLong;
//                }else{
//                    range = 50;
//                }
                range = 0;
                etAddr.setHint(R.string.location_hint);
                setTitle(R.string.location);
                tvRangeLabel.setVisibility(View.GONE);
//                rangeRadioGroup.setVisibility(View.GONE);
                mSeekBar.setVisibility(View.GONE);
//                initRadioGroup();
                break;
            case 2:
                initLinkageConditionData();
                if(scopeLong > 0){
                    range = scopeLong;
                }else{
                    range = 50;
                }
                etAddr.setHint(R.string.location_hint);
                setTitle(R.string.location);
//                initRadioGroup();
                initSeekBar();
                break;
        }
        setOnClickListener(R.id.iv_location);
        /*InputTextManager.with(this)
                .addView(etAddr)
                .setMain(getTitleBar().getRightView())
                .build();*/
        initMapListener();
        initGeocodeSearch();
        //initRangeProgess();
        initPoiSearch();
        initPoilist();
        initPermission();
    }

    private LinkageBean mLinkageBean;
    private LinkageBean.LinkageCondition mLinkageCondition;
    private String areaName;
    private String areaCoding;
    private double latitude;
    private double longitude;
    private int scopeLong;
    private String briefing;
    private void initLinkageConditionData(){
        String linkageSerialNo = getString("serial_no");
        mLinkageBean = LinkageDataHolder.getLinkageData();
        if (mLinkageBean != null) {
            List<LinkageBean.LinkageCondition> linkageConditions = mLinkageBean.getLinkageConditions();
            if (linkageConditions != null && linkageConditions.size() > 0 && !TextUtils.isEmpty(linkageSerialNo)) {
                for (LinkageBean.LinkageCondition item : linkageConditions) {
                    if (item.getConditionSerialNo().equals(linkageSerialNo)) {
                        mLinkageCondition = item;
                        areaName = mLinkageCondition.getAreaName();
                        areaCoding = mLinkageCondition.getAreaCoding();
                        latitude = mLinkageCondition.getLatitude();
                        longitude = mLinkageCondition.getLongitude();
                        scopeLong = mLinkageCondition.getScopeLong();
                        briefing = mLinkageCondition.getBriefing();
                        mLocationData = new LocationData();
                        mLocationData.location = longitude + ":" + latitude;
                        mLocationData.scopeLong = scopeLong;
                        break;
                    }
                }
            }
        }
    }

    @Override
    public void onRightClick(View view) {
        if (isSearching) {
            toast(R.string.house_location_search_fail);
            return;
        }
        if (regeocodeResult != null) {
            LatLng latLng = aMap.getCameraPosition().target;
            String locationStr = LocationUtil.getLocationStr(latLng);
            String locationName = LocationUtil.getLocationName(regeocodeResult);
            LocationData result = new LocationData();
            result.location = locationStr;
            result.locationCN = locationName;
            String townCode = regeocodeResult.getRegeocodeAddress().getTowncode();
            if (townCode != null && townCode.length() >= 6) {
                result.provinceId = townCode.subSequence(0, 2).toString();
                result.cityId = townCode.subSequence(2, 4).toString();
                result.districtId = townCode.subSequence(4, 6).toString();
            }
            result.province = regeocodeResult.getRegeocodeAddress().getProvince();
            result.city = regeocodeResult.getRegeocodeAddress().getCity();
            result.district = regeocodeResult.getRegeocodeAddress().getDistrict();
            result.longitude = latLng.longitude;
            result.latitude = latLng.latitude;
            result.scopeLong = range;
            areaName = result.province + " " + result.city + " " + result.district;
            areaCoding = result.provinceId + result.cityId + result.districtId;
            latitude = result.latitude;
            longitude = result.longitude;
            scopeLong = result.scopeLong;
            briefing = regeocodeResult.getRegeocodeAddress().getFormatAddress();
            //actionUpdateLocation(locationStr, locationName);
            //设置定位联动条件
            if(type == 2){
                //当前联动空，才去
                if (mLinkageCondition == null) {
                    //本地保存联动条件
                    if (mLinkageBean == null) {
                        mLinkageBean = new LinkageBean();
                        LinkageDataHolder.setLinkageData(mLinkageBean);
                    }
                    List<LinkageBean.LinkageCondition> linkageConditions = mLinkageBean.getLinkageConditions();
                    if (linkageConditions == null) {
                        linkageConditions = new ArrayList<>();
                    }
                    mLinkageBean.setLinkageConditions(linkageConditions);
                    mLinkageCondition = new LinkageBean.LinkageCondition();
                    //先设置个本地的SerialNo，为了编辑找到对应的数据
                    mLinkageCondition.setConditionSerialNo(UUID.randomUUID().toString());
                    mLinkageCondition.setConditionType(7);
                    linkageConditions.add(mLinkageCondition);
                    mLinkageCondition.setSort(linkageConditions.indexOf(mLinkageCondition) + 1);
                }
                mLinkageCondition.setAreaType(2);
                mLinkageCondition.setAreaName(areaName);
                mLinkageCondition.setAreaCoding(areaCoding);
                mLinkageCondition.setLongitude(longitude);
                mLinkageCondition.setLatitude(latitude);
                mLinkageCondition.setScopeLong(scopeLong);
                mLinkageCondition.setImageUrl("Location");
                mLinkageCondition.setBriefing(briefing);
                startActivity_SingleTask(EditLinkageActivity.class);
                finish();
            }else{
                Intent intent = new Intent();
                intent.putExtra("DATA", result);
                setResult(RESULT_OK, intent);
                finish();
            }
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_location;
    }

    @Override
    protected void initView() {

    }

    private void initSeekBar(){
        tvRangeLabel.setVisibility(View.VISIBLE);
        mSeekBar.setVisibility(View.VISIBLE);
        mSeekBar.setOnSeekBarChangeListener(new MySeekBar.OnSeekBarChangeListener() {
            @Override
            public void onValueChanged(int value) {

            }

            @Override
            public void onStartTrackingTouch() {

            }

            @Override
            public void onStopTrackingTouch(int value) {
                range = value;
                refreshOverlayWidth();
            }
        });
        mSeekBar.setValue(range);
    }

    @Override
    protected void initData() {

    }

    @Permissions({ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION,ACCESS_BACKGROUND_LOCATION})
    public static void startForResult(BaseActivity activity, LocationData locationData, int requestCode) {
        Intent intent = new Intent(activity, LocationActivity.class);
        intent.putExtra("DATA", locationData);
        activity.startActivityForResult(intent, requestCode);
    }

    @Permissions({ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION,ACCESS_BACKGROUND_LOCATION})
    public static void startForResult(BaseActivity activity, LocationData locationData, int type, int requestCode) {
        Intent intent = new Intent(activity, LocationActivity.class);
        intent.putExtra("DATA", locationData);
        intent.putExtra("type", type);
        activity.startActivityForResult(intent, requestCode);
    }

    @Permissions({ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION,ACCESS_BACKGROUND_LOCATION})
    public static void start(BaseActivity activity, String serialNo, int type) {
        Intent intent = new Intent(activity, LocationActivity.class);
        intent.putExtra("serial_no", serialNo);
        intent.putExtra("type", type);
        activity.startActivity(intent);
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onResume() {
        super.onResume();
        map.onResume();
        xxPermissions.permission(needPermissions)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        initLocation();
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            ToastUtils.show(R.string.common_permission_fail_1);
                            finish();
                            return;
                        }
                        ToastUtils.show(R.string.common_permission_fail_1);
                    }

                });
        if (!isMoveToLocation) {
            initLocationStr();
            isMoveToLocation = false;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_location:
//                moveToNowLocation();
                if (XXPermissions.isGranted(this, needPermissions)) {
                    moveToNowLocation();
                } else {
                    isMoveToLocation = true;
                }
                break;
            default: {

            }
        }
    }

    private void initPoilist() {
        locList.setLayoutManager(new LinearLayoutManager(this));
        houseLocationAdapter = new AddressAdapter();
        houseLocationAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                Tip tip = houseLocationAdapter.getData().get(position);
                etAddr.removeTextChangedListener(textWatcher);
                etAddr.setText(tip.getName());
                etAddr.clearFocus();
                hideKeyboard(getCurrentFocus());
                etAddr.addTextChangedListener(textWatcher);
                locList.setVisibility(View.GONE);
                searchLine.setVisibility(locList.getVisibility());
                if (tip != null) {
                    LatLng latLng = new LatLng(tip.getPoint().getLatitude(), tip.getPoint().getLongitude());
                    aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
                }
            }
        });
        locList.setAdapter(houseLocationAdapter);
    }

    private TextWatcher textWatcher;

    private void initPoiSearch() {
        if (textWatcher == null) {
            textWatcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    inputStr = s.toString();
                    if (!TextUtils.isEmpty(s.toString())) {
                        searchPoi(s.toString());
                    } else {
                        locList.setVisibility(View.GONE);
                        searchLine.setVisibility(locList.getVisibility());
                    }
                }
            };
        }
        etAddr.addTextChangedListener(textWatcher);
    }

    private void searchPoi(String search) {
        PoiSearch.Query query = new PoiSearch.Query(search, "", "");
        InputtipsQuery inputquery = new InputtipsQuery(search, "");
        Inputtips inputTips = new Inputtips(this, inputquery);
        inputTips.setInputtipsListener(this);
        inputTips.requestInputtipsAsyn();
//        query.setPageSize(10);
//        query.setPageNum(0);
//        if (poiSearch == null) {
//            poiSearch = new PoiSearch(this, query);
//            poiSearch.setOnPoiSearchListener(this);
//        } else {
//            poiSearch.setQuery(query);
//        }
//        poiSearch.searchPOIAsyn();
    }

    private void initPermission() {
        xxPermissions = XXPermissions.with(this);
        if (Build.VERSION.SDK_INT > 28
                && getApplicationContext().getApplicationInfo().targetSdkVersion > 28) {
            needPermissions = new String[]{
                    ACCESS_COARSE_LOCATION,
                    ACCESS_FINE_LOCATION,
                    BACKGROUND_LOCATION_PERMISSION
            };
        }
    }

    private void initGeocodeSearch() {
        geocodeSearch = new GeocodeSearch(this);
        geocodeSearch.setOnGeocodeSearchListener(this);
    }

    private void initMapListener() {
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
                isSearching = true;
                refreshOverlayWidth();
            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                refeshLocationInfo(cameraPosition.target);
            }
        });

        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {

            }
        });
    }

    private void refreshOverlayWidth() {
        float scale = aMap.getScalePerPixel();
        float pixelRange = range / scale;
        if (mapOver != null) {
            mapOver.setRadius((int) pixelRange);
        }
    }

    public void refeshLocationInfo(LatLng latLng) {
        LatLonPoint latLonPoint = new LatLonPoint(latLng.latitude, latLng.longitude);
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);
        if (geocodeSearch != null) {
            geocodeSearch.getFromLocationAsyn(query);
        }
    }

    private void initLocationStr() {
        if (mLocationData != null) {
            String locationStr = mLocationData.location;
            String[] locations = locationStr.split(":");
            double lat = Double.valueOf(locations[1]);
            double lng = Double.valueOf(locations[0]);
            if (lat == 0 || lng == 0) {
                isNeedMoveToNowLocation = true;
                if (aMapLocation != null) {
                    moveToNowLocation();
                }
            } else {
                LatLng latLng = new LatLng(lat, lng);
                LatLonPoint latLonPoint = new LatLonPoint(Double.valueOf(locations[1]), Double.valueOf(locations[0]));
                RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);
                if (geocodeSearch != null) {
                    geocodeSearch.getFromLocationAsyn(query);
                }
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
            }
        } else {
            isNeedMoveToNowLocation = true;
            if (aMapLocation != null) {
                moveToNowLocation();
            }
        }
    }

    private void moveToNowLocation() {
        boolean isOpen =  LocationUtil.isOPen(this);

        if (isOpen) {
            if (aMapLocation != null) {
                LatLng latLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
            } else {
                ToastUtils.show(R.string.no_location_alert);
            }
        } else {
//            openLocationSettings(this);
            ToastUtils.show(R.string.no_location_alert);
        }
    }

    public static void openLocationSettings(Context context) {
        Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        context.startActivity(intent);
    }


    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private GeocodeSearch geocodeSearch;
    private AMap aMap;

    private void initLocation() {
        //初始化client
        locationClient = new AMapLocationClient(this.getApplicationContext());
        locationOption = getDefaultOption();
        //设置定位参数
        locationClient.setLocationOption(locationOption);
        // 设置定位监听
        locationClient.setLocationListener(this);
        locationClient.startLocation();
    }

    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        //可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(2000);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(true);//可选，设置是否单次定位。默认是false
        //可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        mOption.setOnceLocationLatest(false);
        //可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，
        // 停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setWifiScan(true);
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        //可选，设置逆地理信息的语言，默认值为默认语言（根据所在地区选择语言）
        mOption.setGeoLanguage(AMapLocationClientOption.GeoLanguage.DEFAULT);
        return mOption;
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        if (regeocodeResult == null) {
            return;
        }
        this.regeocodeResult = regeocodeResult;
        isSearching = false;
        etAddr.setHint(regeocodeResult.getRegeocodeAddress().getFormatAddress());
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }

    private AddressAdapter houseLocationAdapter;

    @Override
    public void onGetInputtips(List<Tip> tipList, int i) {
        if (houseLocationAdapter != null) {
            List<Tip> tips = new ArrayList<>();
            for (Tip tip : tipList) {
                if (tip.getPoint() == null) {
                    continue;
                }
                if (!TextUtils.isEmpty(tip.getAddress()) || !TextUtils.isEmpty(tip.getName())) {
                    tips.add(tip);
                }
            }
            if (tips.size() == 0) {
                locList.setVisibility(View.GONE);
                tvSearchNoData.setVisibility(inputStr.isEmpty() ? View.GONE : View.VISIBLE);
                searchLine.setVisibility(tvSearchNoData.getVisibility());
                tvSearchNoData.setText(getString(R.string.selected_no_data, inputStr));
            } else {
                tvSearchNoData.setVisibility(View.GONE);
                //加个判断，在删除快的时候，搜索返回了，但是EditText已经没有搜索内容了
                if(etAddr.getText().length() > 0){
                    locList.setVisibility(View.VISIBLE);
                    searchLine.setVisibility(searchLine.getVisibility());
                    houseLocationAdapter.setSearchStr(etAddr.getText().toString());
                    houseLocationAdapter.setNewInstance(tips);
                    houseLocationAdapter.notifyDataSetChanged();
                }
            }
        }
    }


    private AMapLocation aMapLocation;
    //是否需要跳转到当前定位位置
    private boolean isNeedMoveToNowLocation = false;

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        this.aMapLocation = aMapLocation;
        if (isNeedMoveToNowLocation) {
            moveToNowLocation();
        }
    }

    private class AddressAdapter extends BaseQuickAdapter<Tip, BaseViewHolder> {
        private String searchStr;

        public AddressAdapter() {
            super(R.layout.item_location);
        }

        @Override
        protected void convert(BaseViewHolder viewHolder, Tip poiItem) {
            String title = poiItem.getName();
            if (!TextUtils.isEmpty(searchStr)) {
                if (title.contains(searchStr)) {
                    int index = title.indexOf(searchStr);
                    SpannableString spannableString = new SpannableString(title);
                    ForegroundColorSpan colorSpan = new ForegroundColorSpan(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
                    spannableString.setSpan(colorSpan, index, index + searchStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    viewHolder.setText(R.id.tv_name, spannableString);
                } else {
                    viewHolder.setText(R.id.tv_name, title);
                }
            }
            String addr = poiItem.getAddress();
            if (addr.isEmpty()) {
                viewHolder.setGone(R.id.tx_address, true);
            } else {
                viewHolder.setGone(R.id.tx_address, false);
            }
            viewHolder.setText(R.id.tx_address, addr);
        }

        public void setSearchStr(String searchStr) {
            this.searchStr = searchStr;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /*if (requestCode == XXPermissions.REQUEST_CODE) {
            if (XXPermissions.isGranted(this, needPermissions)){
                initLocation();
            }
        }*/
    }

    @Override
    protected void onPause() {
        super.onPause();
        map.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        map.onDestroy();
        destroyLocation();
    }

    private void destroyLocation() {
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }
}